package com.ogilvy.audi.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.ogilvy.audi.service.CircleAcmntManager;
import com.ogilvy.audi.model.CircleAcmnt;
import com.ogilvy.audi.webapp.action.BaseAction;

import java.util.List;

public class CircleAcmntAction extends BaseAction implements Preparable {
    private CircleAcmntManager circleAcmntManager;
    private List circleAcmnts;
    private CircleAcmnt circleAcmnt;
    private Long cmtId;
    private String query;

    public void setCircleAcmntManager(CircleAcmntManager circleAcmntManager) {
        this.circleAcmntManager = circleAcmntManager;
    }

    public List getCircleAcmnts() {
        return circleAcmnts;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String circleAcmntId = getRequest().getParameter("circleAcmnt.cmtId");
            if (circleAcmntId != null && !circleAcmntId.equals("")) {
                circleAcmnt = circleAcmntManager.get(new Long(circleAcmntId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        circleAcmnts = circleAcmntManager.search(query, CircleAcmnt.class);
        return SUCCESS;
    }

    public void setCmtId(Long cmtId) {
        this.cmtId = cmtId;
    }

    public CircleAcmnt getCircleAcmnt() {
        return circleAcmnt;
    }

    public void setCircleAcmnt(CircleAcmnt circleAcmnt) {
        this.circleAcmnt = circleAcmnt;
    }

    public String delete() {
        circleAcmntManager.remove(circleAcmnt.getCmtId());
        saveMessage(getText("circleAcmnt.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (cmtId != null) {
            circleAcmnt = circleAcmntManager.get(cmtId);
        } else {
            circleAcmnt = new CircleAcmnt();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (circleAcmnt.getCmtId() == null);

        circleAcmntManager.save(circleAcmnt);

        String key = (isNew) ? "circleAcmnt.added" : "circleAcmnt.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}